<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery\channel;

use app\common\model\delivery\Driver;
use app\common\model\delivery\ChannelGird;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use think\annotation\route\Route;

#[Group("delivery/channel-gird")]
class Gird extends ChannelBase
{
    use Actions{
        del as private _del;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new ChannelGird();
        $this->postParams['channel_id']=$this->channel->id;
    }

    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            return $this->selectpage();
        }
        $where = [];
        $where[] = ['channel_id','=',$this->channel->id];
        [$where, $order, $limit] = $this->buildparams($where);
        $driver=Driver::where(['channel_id'=>$this->channel->id])->select();
        $list = $this->model
            ->where($where)
            ->order($order)
            ->paginate($limit)
            ->each(function ($res) use ($driver){
                if($res->drivers){
                    $driver_ids=explode(',',$res->drivers);
                    $drivers=[];
                    foreach ($driver as $value){
                        foreach ($driver_ids as $driver_id){
                            if(intval($driver_id)==$value->id){
                                $drivers[]=$value;
                            }
                        }
                    }
                    $res->drivers=$drivers;
                }
            });
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    #[Route('GET,POST','del')]
    public function del()
    {
        $ids = $this->request->param("ids");
        if(\app\common\model\Customer::whereIn('gird_id',$ids)->count()>0){
            $this->error('网格下存在公司，无法删除');
        }
        return $this->_del();
    }
}